<template>
  <div>
    <Col>
      <Card class="warp-card" dis-hover>
        <!--Row 顶部操作区 start-->
        <Row justify="space-between" type="flex">
          <Col>
            <span>
              账号 :
              <Input
                placeholder="请输入账号"
                style="width: 180px"
                v-model="queryForm.loginName"
              />
            </span>
            <span>
              昵称 :
              <Input
                placeholder="请输入昵称"
                style="width: 180px"
                v-model="queryForm.actualName"
              />
            </span>
            <span>
              状态 :
              <Select v-model="queryForm.isDisabled" style="width: 180px">
                <Option value="0">启用</Option>
                <Option value="1">禁用</Option>
              </Select>
            </span>
            <ButtonGroup style="margin-left:20px">
              <Button @click="searchEmployees" icon="ios-search" type="primary"
                >查询</Button
              >
              <Button @click="resetQueryList" icon="md-refresh" type="default"
                >重置</Button
              >
            </ButtonGroup>
          </Col>
          <Col>
            <!-- <Button
              @click="queryEmployeeListByIsDisabled(1)"
              type="default"
              v-privilege="'search-department'"
              v-show="!currentDisabled"
              >查看已禁用用户</Button
            >
            <Button
              @click="queryEmployeeListByIsDisabled(0)"
              type="default"
              v-privilege="'search-department'"
              v-show="currentDisabled"
              >查看已启用用户</Button
            >
            <Button
              @click="GroupDisable(1)"
              style="margin-left:5px"
              type="error"
              v-privilege="'disabled-employee-batch'"
              v-show="!currentDisabled"
              >批量禁用</Button
            >
            <Button
              @click="GroupDisable(0)"
              style="margin-left:5px"
              type="success"
              v-privilege="'disabled-employee-batch'"
              v-show="currentDisabled"
              >批量启用</Button
            > -->
          </Col>
        </Row>
        <Row class="card_top" justify="space-between" style="margin-top:20px">
          <Col span="12" push="0.2">
            用户列表
          </Col>
          <Col span="11" class="col_right">
            共注册
            <span style="color:red">{{ totalPage }}</span> 位用户
          </Col>
        </Row>
        <!--Row 顶部操作区 end-->
        <!--Row 表格区 start-->
        <Row style="padding-top:10px; ">
          <Table
            :columns="columns"
            :data="employeeTable"
            :loading="isShowTablesLoading"
            @on-selection-change="singleSelect"
            border
          ></Table>
        </Row>
        <!--Row 表格区 end-->
        <!--Row 底部操作区 start-->
        <Row
          class="page"
          justify="end"
          style="position: relative;margin-top: 10px;"
          type="flex"
        >
          <Page
            :current="pageNum"
            :page-size="pageSize"
            :total="totalPage"
            @on-change="changePage"
            show-elevator
          ></Page>
        </Row>
        <!--Row 底部操作区 end-->
      </Card>
    </Col>
    <!--EmployeeTableAdd 添加成员弹窗 start-->
    <EmployeeTableAdd
      :selectDepartment="selectDepartment"
      @addSuccess="getEmployeeList"
      ref="employeeTableAdd"
    ></EmployeeTableAdd>
    <!--EmployeeTableAdd 添加成员弹窗 end-->
    <!--Modal 角色管理弹窗 start-->
    <Modal
      @on-ok="confirmAddRole"
      class-name="vertical-center-modal"
      title="角色设置"
      v-model="isShowManageRoleModal"
    >
      <RadioGroup v-model="employeeRole">
        <Radio
          :key="roleItem.id"
          :label="roleItem.id"
          style="width:104px;line-height:40px;"
          v-for="roleItem in roleList"
          >{{ roleItem.roleName }}</Radio
        >
      </RadioGroup>
    </Modal>
    <!--Modal 角色管理弹窗 end-->
    <!--EmployeeTableDetail 角色详情 start-->
    <EmployeeTableDetail ref="employeeTableDetail"></EmployeeTableDetail>
    <!--EmployeeTableDetail 角色详情 end-->
  </div>
</template>
<script>
import { departmentApi } from "@/api/department";
import { employeeApi } from "@/api/employee";
import { roleApi } from "@/api/role";
import { utils } from "@/lib/util";
import EmployeeTableAdd from "../employee-table-add/employee-table-add.vue";
import EmployeeTableDetail from "../employee-table-detail/employee-table-detail.vue";
export default {
  name: "EmployeeTable",
  components: {
    EmployeeTableAdd,
    EmployeeTableDetail
  },
  props: {
    // 选中的部门
    selectDepartment: {
      type: Object,
      required: true
    },
    // 表格样式 按钮功能
    departments: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      employeeRole: 1,
      // 员工id
      mid: "",
      totalPage: 0,
      pageSize: 20,
      pageNum: 1,
      queryForm: {
        actualName: "",
        loginName: "",
        isDisabled: null
      },
      isShowManageRoleModal: false,
      isShowTablesLoading: false,
      // 搜索框内容
      searchEmployeeName: "",
      columns: [
        // {
        //   title: "ID",
        //   key: "id",
        //   width: 60
        // },

        {
          key: "loginName",
          title: "用户账号",
          align: "left"
        },
        {
          key: "actualName",
          title: "用户昵称",
          align: "left"
        },
        // {
        //   key: "email",
        //   title: "用户Email",
        //   align: "left"
        // },

        {
          key: "isDisabled",
          title: "状态",
          align: "left",
          render: (h, params) => {
            let disabled = params.row.isDisabled;
            return h("span", disabled ? "禁用" : "启用");
          }
        },
        {
          title: "操作",
          key: "action",
          width: 200,
          align: "left",
          className: "action-hide",
          render: (h, params) => {
            let btnGroup = [];
            let isSuper = params.row.super || params.row.id == 11;
            // if (!isSuper && params.row.roleId != 1) {
            //   btnGroup.push({
            //     title: "角色设置",
            //     directives: [
            //       {
            //         name: "privilege",
            //         value: "update-employee-role"
            //       }
            //     ],
            //     action: () => {
            //       this.showManageRoleModal(h, params);
            //     }
            //   });
            // }

            // if (
            //   params.row.isDisabled == 0 &&
            //   !isSuper &&
            //   params.row.roleId != 1
            // ) {
            //   btnGroup.push({
            //     title: "编辑",
            //     directives: [
            //       {
            //         name: "privilege",
            //         value: "update-employee"
            //       }
            //     ],
            //     action: () => {
            //       this.updataEmployee(params.row);
            //     }
            //   });
            // }
            if (!isSuper) {
              let isDisableBtn;
              if (params.row.isLeave == 0) {
                isDisableBtn = {
                  title: "审核通过",
                  action: () => {
                    this.updateEmployeeLeave(h, params);
                  }
                };
              } else if (params.row.isDisabled == 0) {
                isDisableBtn = {
                  title: "禁用",
                  action: () => {
                    this.updateEmployeeStatus(h, params);
                  }
                };
              } else {
                isDisableBtn = {
                  title: "启用",
                  action: () => {
                    this.updateEmployeeStatus(h, params);
                  }
                };
              }
              btnGroup.push(isDisableBtn);
            }
            if (!isSuper && params.row.isLeave == 1) {
              btnGroup.push({
                title: "密码重置",
                action: () => {
                  this.$Modal.confirm({
                    title: "重置密码",
                    content: "是否将密码重置为123456",
                    onOk: () => {
                      this.resetPassword(params.row.id);
                    }
                  });
                }
              });
            }

            // return h('div', btnGroup)
            return this.$tableAction(h, btnGroup);
          }
        }
      ],
      // 表格数据
      employeeTable: [],
      disableId: [],
      currentDisabled: 0,
      roleList: []
    };
  },
  computed: {},
  watch: {
    selectDepartment(newData) {
      this.selectDepartment = newData;
      this.pageNum = 1;
      this.getEmployeeList();
    }
  },
  filters: {},
  created() {},
  mounted() {
    this.getEmployeeList();
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  methods: {
    //重置查询
    resetQueryList() {
      this.pageNum = 1;
      this.queryForm = {
        actualName: "",
        loginName: "",
        isDisabled: null
      };
      this.getEmployeeList();
    },
    async updateEmployeeLeave(h, params) {
      params.row.isLeave = 1;
      try {
        this.isShowLoading = true;
        let result = await employeeApi.updateEmployee(params.row);
        this.isShowAddOrUpdateEmployeeModal = false;
        this.$Message.success("审核成功");
        this.$emit("addSuccess");
        this.$refs["formValidate"].resetFields();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowLoading = false;
      }
    },
    // 翻页
    changePage(pageNum) {
      this.pageNum = pageNum;
      this.getEmployeeList();
    },
    // 根据部门ID查询部门员工
    async getEmployeeList() {
      let param = {
        // isDisabled: this.currentDisabled,
        pageSize: this.pageSize,
        pageNum: this.pageNum
      };
      param.departmentId = this.selectDepartment.id;
      var queryForm = this.queryForm;
      param = {
        ...param,
        actualName: queryForm.actualName,
        loginName: queryForm.loginName,
        isDisabled: queryForm.isDisabled
      };
      try {
        this.isShowTablesLoading = true;
        param.keyword = this.searchEmployeeName;
        let result = await employeeApi.getEmployeeList(param);
        this.totalPage = result.data.total;
        this.employeeTable = result.data.list;
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowTablesLoading = false;
      }
    },
    // 打开子组件的模态框
    showAddEmployeeModal() {
      this.$refs.employeeTableAdd.showModal();
    },
    // 根据是否启用查询成员
    queryEmployeeListByIsDisabled(type) {
      this.currentDisabled = type;
      this.pageNum = 1;
      this.getEmployeeList();
    },
    // 确定添加角色
    async confirmAddRole() {
      let roleList = this.employeeRole;
      try {
        this.isShowTablesLoading = true;
        let result = await employeeApi.updateRoles(
          Object.assign({
            employeeId: this.mid,
            roleId: roleList
          })
        );
        this.isShowTablesLoading = false;
        this.$Message.success("授权成功");
        this.getEmployeeList();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowTablesLoading = false;
      }
    },
    // 确认添加角色的后台数据接口
    async getRoles(id) {
      try {
        this.isShowTablesLoading = true;
        let result = await roleApi.getRoles(id);
        this.isShowTablesLoading = false;
        this.roleList = result.data;
        this.roleList = this.roleList.splice(1, 7);
        this.roleList.forEach(item => {
          if (item.selected) {
            this.employeeRole = item.id;
          }
        });
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowTablesLoading = false;
      }
    },
    // 点击打开员工角色选择框
    showManageRoleModal(h, param) {
      this.mid = param.row.id;
      this.isShowManageRoleModal = true;
      this.getRoles(param.row.id);
    },
    // 修改员工信息
    updataEmployee(detail) {
      if (this.departments[0].id == detail.departmentId) {
        detail.departmentName = this.departments[0].name;
      } else {
        this.departments[0].children.forEach(item => {
          if (item.id == detail.departmentId) {
            detail.departmentName = item.name;
          }
        });
      }
      if (detail.birthday) {
        detail.birthday = utils.getDate(new Date(detail.birthday), "YMD");
      }
      this.$refs.employeeTableAdd.showModal(detail);
    },
    // 点击搜索
    searchEmployees() {
      this.pageNum = 1;
      this.queryEmployeeListByIsDisabled(0);
    },
    // 表格左侧复选框，点击保存选中栏信息
    singleSelect(row) {
      this.disableId = row;
    },
    // 批量禁用
    GroupDisable(type) {
      if (this.disableId.length == 0) {
        this.$Message.error("请最少选择一项");
        return false;
      } else {
        this.currentDisabled = type;
        let disableIds = this.disableId.map(e => e.id);
        this.updateStatusBatch(
          Object.assign({ status: type, employeeIds: disableIds })
        );
      }
    },
    // 禁用/启用单个用户
    async updateEmployeeStatus(h, params) {
      try {
        this.isShowTablesLoading = true;
        let employeeId = params.row.id;
        let status = 0;
        if (params.row.isDisabled == 0) {
          status = 1;
          this.queryEmployeeListByIsDisabled(0);
        } else {
          status = 0;
          this.queryEmployeeListByIsDisabled(1);
        }
        let result = await employeeApi.updateStatus(employeeId, status);
        this.isShowTablesLoading = false;
        if (status) {
          this.$Message.success("禁用成功");
          this.getEmployeeList();
        } else {
          this.$Message.success("启用成功");
          this.queryEmployeeListByIsDisabled(1);
        }
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowTablesLoading = false;
      }
    },
    // 批量禁用多个用户
    async updateStatusBatch(param) {
      try {
        this.isShowTablesLoading = true;
        let result = await employeeApi.updateStatusBatch(param);
        this.isShowTablesLoading = false;
        this.$Message.success("操作成功");
        this.disableId = [];
        this.queryEmployeeListByIsDisabled(this.currentDisabled);
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowTablesLoading = false;
      }
    },
    // 重置密码
    async resetPassword(id) {
      try {
        this.isShowTablesLoading = true;
        let result = await employeeApi.resetPassword(id);
        this.isShowTablesLoading = false;
        this.$Message.success("操作成功");

        this.queryEmployeeListByIsDisabled(this.currentDisabled);
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowTablesLoading = false;
      }
    },
    // 删除成员
    async deleteEmployee(id) {
      try {
        this.isShowTablesLoading = true;
        let result = await employeeApi.deleteEmployee(id);
        this.isShowTablesLoading = false;
        this.$Message.success("操作成功");
        this.queryEmployeeListByIsDisabled(this.currentDisabled);
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowTablesLoading = false;
      }
    }
  }
};
</script>
<style lang="less" scoped>
.ivu-tree-children {
  cursor: pointer;
}

.option-department {
  font-size: 14px;
  padding: 5px;
  cursor: pointer;
}

.searchable-table-con1 {
  min-height: 350px !important;
}

.option-department:hover {
  background-color: rgba(5, 170, 250, 0.2);
}
</style>
